package com.lucanjun.cn.springboot.multipledatasources.common.exception;

import com.lucanjun.cn.springboot.multipledatasources.common.result.HttpResult;
import com.lucanjun.cn.springboot.multipledatasources.common.result.HttpResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author lucanjun
 * @version 1.0.0
 * @title GlobalExceptionHandler
 * @create 2024-12-19 16:55:19
 * @description 全局异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    //自定义异常处理
    @ExceptionHandler(BusinessException.class)
    public HttpResult businessException(BusinessException e) {
        e.printStackTrace();
        return HttpResult.returnFail(e.getCode(), e.getMessage());
    }

    //全局异常处理
    @ExceptionHandler(Exception.class)
    public HttpResult globalException(Exception e) {
        e.printStackTrace();
        return HttpResult.returnFail(HttpResultCodeEnum.FAIL);
    }

    //特定异常处理
    @ExceptionHandler(ArithmeticException.class)
    public HttpResult arithmeticException(ArithmeticException e) {
        e.printStackTrace();
        String message = e.getMessage();
        return HttpResult.returnFail(message);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public HttpResult<Void> exceptionHandler(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        log.error(message, e);
        HttpResult<Void> result = HttpResult.returnFail(message);
        return result;
    }

}
